package com.seal.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.seal.comm.utils.Page;
import com.seal.dao.BaseDaoImpl;
import com.seal.dao.INoticeDao;
import com.seal.dto.NoticeDto;
import com.seal.model.Notice;

@Repository("noticeDaoImpl")
public class NoticeDaoImpl extends BaseDaoImpl implements INoticeDao{

	public void addNotice(Notice ca) throws Exception {
		this.save(ca);
	}

	public void updateNotice(Notice ca) throws Exception {
		this.update(ca);
	}
	
	public void deleteNotice(Notice ca) throws Exception {
		this.delete(ca);
	}
	
	public Notice getNoticeById(Long id) throws Exception {
		return (Notice) this.select(Notice.class, id);
	}
	
	public List<Notice> getAllNotice(NoticeDto noticeDto, Page page)throws Exception {
		StringBuffer hql=new StringBuffer("from Notice t where 1=1");
		if (null != noticeDto.getFromDate()) {
			hql.append(" and t.startDate <= :fromDate");
		}
		
		if (null != noticeDto.getToDate()) {
			hql.append(" and t.endDate >= :toDate");
		}
		
		if (null != noticeDto.getStatus()) {
			hql.append(" and t.status = :status");
		}
		
		if (null != noticeDto.getType()) {
			hql.append(" and t.type = :type");
		}
		
		if (null != noticeDto.getSubtype()) {
			hql.append(" and t.subtype = :subtype");
		}
		
		if (null != noticeDto.getLang()) {
			hql.append(" and t.lang = :lang");
		}
		hql.append(" order by orderNum asc");
		
		Query query = this.getSession().createQuery(hql.toString());
		query.setProperties(noticeDto);
		if (null != page) {
			query.setFirstResult(page.getFirstResult());
			query.setMaxResults(page.getPageSize());
			String countSql="select count(t) "+hql.toString();

			Query queryCount = this.getSession().createQuery(countSql);
			queryCount.setProperties(noticeDto);
			page.setTotalNumber(Integer.parseInt(queryCount.uniqueResult().toString()));
		}
		
		return query.list();
	}
}
